﻿////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// <copyright>Copyright 2008-2011 Andreas Huber Doenni</copyright>
// Distributed under the Microsoft Public License (Ms-PL).
// See accompanying file License.txt or copy at http://mews.codeplex.com/license.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

namespace Mews.Mime
{
    using System;
    using System.IO;
    using System.Text;

    using Mews.IO;

    /// <summary>Processes unstructured text content with a given encoding and encoding transformation.</summary>
    internal class UnstructuredTextProcessor : UnstructuredContentProcessor
    {
        private readonly Encoding encoding;

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        internal UnstructuredTextProcessor(EncodingTransformation encodingTransformation, Encoding encoding) :
            base(encodingTransformation)
        {
            this.encoding = encoding;
        }

        /// <summary>Gets the processed text.</summary>
        /// <exception cref="InvalidOperationException"><see cref="GetText"/> has been called before (it may only be
        /// called once).</exception>
        internal string GetText()
        {
            int dummy;

            // The line endings of text with a Content-Transfer-Encoding of base64 could not be fixed while
            // communicating with the server. Since we don't know the Content-Transfer-Encoding of the original content
            // we have to use FixLineEndindsStream here for all cases, which makes this method a bit inefficient when
            // the Content-Transfer-Encoding is 7bit, 8bit or quoted-printable.
            using (var fixStream = new FixLineEndingsStream(this.GetContent(out dummy)))
            using (var stream = this.AddCustomTransformation(fixStream))
            using (var reader = new StreamReader(stream, this.encoding, false, Settings.InMemoryStreamBufferSize))
            {
                return reader.ReadToEnd();
            }
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>Returns <paramref name="content"/>.</summary>
        /// <remarks>If necessary, deriving classes can wrap <paramref name="content"/> in a new stream, which
        /// transforms the content as necessary.</remarks>
        protected virtual Stream AddCustomTransformation(Stream content)
        {
            return content;
        }
    }
}
